package com.application.moneycalculator.activity;

import java.io.File;
import java.io.IOException;

import com.application.moneycalculator.R;
import com.application.moneycalculator.data.ExpenseItem;
import com.application.moneycalculator.log.Log_;
import com.application.moneycalculator.utils.DateUtils;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class ExpenseActivity extends BaseActivity {
	private final String TAG = "ExpenseActivity";
	
    private Button doneButton;
    private Button attachButton;
    
    private ImageView cameraPicture;
    
    private String filePath;
	
	// The different distinct states the activity can be run in.
    private static final int STATE_EDIT = 0;
    private static final int STATE_INSERT = 1;
    private int state = STATE_EDIT;
    
    private final String TAKEN_IMAGE_PATH_KEY = "image_from_camera";
    
    
    /** Called when the activity is first created. */
    @Override
	public void onCreate(Bundle savedInstanceState) {
    	Log_.out(TAG, "onCreate start");
        super.onCreate(savedInstanceState);

        final Intent intent = getIntent();
        
        final String action = intent.getAction();
        if (Intent.ACTION_EDIT.equals(action)) {
        	state = STATE_EDIT;
            //mUri = intent.getData();
        } else if (Intent.ACTION_INSERT.equals(action)) {
            // Requested to insert: set that state, and create a new entry
            // in the container.
        	state = STATE_INSERT;
            //mUri = getContentResolver().insert(intent.getData(), null);

            // If we were unable to create a new note, then just finish
            // this activity.  A RESULT_CANCELED will be sent back to the
            // original activity if they requested a result.
            /*if (mUri == null) {
                Log_.out(this, "Failed to insert new note into " + getIntent().getData());
                finish();
                return;
            }*/

            // The new entry was created, so assume all will end well and
            // set the result to be returned.
            //setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));

        } else {
            // Whoops, unknown action!  Bail.
            Log_.out(TAG, "Unknown action, exiting");
            finish();
            return;
        }

        setContentView(R.layout.expense);
        
        //handle pressing to Done button
        doneButton = (Button) findViewById(R.id.button_done_expenses);
        //doneButton.requestFocus();
        doneButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log_.out(TAG, "Done button is pressed");
				finish();
			}
		});
        
        //handle pressing to Attach button
        attachButton = (Button) findViewById(R.id.button_attach_expenses);
        attachButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log_.out(TAG, "Attach button is pressed");
				launchCameraApplication();
			}
		});
        
        cameraPicture = (ImageView) findViewById(R.id.expense_camera_picture);
        Log_.out(TAG, "onCreate finish");
    }
    
    @Override
    protected void onDestroy() {
    	Log_.out(TAG, "onDestroy");
    	super.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	Log_.out(TAG, "onSaveInstanceState");
    	super.onSaveInstanceState(outState);
    	
    	Log_.out(TAG, "Trying to save path [" + filePath + "]");
    	outState.putString(TAKEN_IMAGE_PATH_KEY, filePath);
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	Log_.out(TAG, "onRestoreInstanceState");
    	super.onRestoreInstanceState(savedInstanceState);
    	String filePath = savedInstanceState.getString(TAKEN_IMAGE_PATH_KEY);
    	if(filePath != null)
    	{
    		Log_.out(TAG, "Restored path [" + filePath + "]");
    	}
    	else
    	{
    		Log_.out(TAG, "There is nothing to restore");
    	}
    }
    
    private final short CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 123;
    private void launchCameraApplication()
    {
    	 Log_.out(TAG, "launchCameraApplication start");
    	 /*
    	//define the file-name to save photo taken by Camera activity
    	String fileName = "new-photo-name.jpg";
    	//create parameters for Intent with filename
    	ContentValues values = new ContentValues();
    	values.put(MediaStore.Images.Media.TITLE, fileName);
    	values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
    	//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
    	Uri imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    	//create new Intent
    	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    	intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    	intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    	startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    	*/
    	 
    	 String storageState = Environment.getExternalStorageState();
         if(storageState.equals(Environment.MEDIA_MOUNTED)) {
        	 Log_.out(TAG, "Flash memory is present");
        	 
        	 filePath = 	Environment.getExternalStorageDirectory().getName() + 
             				File.separatorChar + "Android/data/" + 
             				ExpenseActivity.this.getPackageName() + 
             				"/files/" + 
             				/*md5(upc)*/
             				DateUtils.convertExpenseToString(new ExpenseItem(DateUtils.getCurrentDate())) + 
             				".jpg";
             
             File photoFile = new File(filePath);
             try {
                 if(photoFile.exists() == false) {
                	 Log_.out(TAG, "Try to create all directory");
                	 photoFile.getParentFile().mkdirs();
                	 Log_.out(TAG, "Try to create file");
                	 photoFile.createNewFile();
                 }
                 else
                 {
                	 Log_.out(TAG, "Directory already exist");
                 }

             } catch (IOException e) {
            	 Log_.out(TAG, "Could not create file");
            	 
             }
             Log_.out(TAG, "Image will be stored here [" + filePath + "]");

             Uri fileUri = Uri.fromFile(photoFile);
             if(fileUri == null)
             {
            	 Log_.out(TAG, "Impossible to create Uri for future image from camera");
             }
             else
             {
            	 Log_.out(TAG, "Uri for future image from camera is created");	 
             }
             
             Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
             intent.putExtra( MediaStore.EXTRA_OUTPUT, fileUri);
             startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
         } 
         else 
         {
             new AlertDialog.Builder(ExpenseActivity.this)
             .setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
             .setCancelable(true).create().show();
         }
    	
    	Log_.out(TAG, "launchCameraApplication finish");
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	Log_.out(TAG, "onActivityResult, requestCode [" + requestCode + "], result [" + resultCode + "]");
    	if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
    	    if (resultCode == RESULT_OK) {
    	    	//use imageUri here to access the image
    	    	Log_.out(TAG, "Picture was taken :)");
    	    	
				if (cameraPicture != null) {
					Log_.out(TAG, "Request file path");
					if (filePath != null) {
						Log_.out(TAG, "Try to create bitmap from [" + filePath + "]");
						Bitmap bit = BitmapFactory.decodeFile(filePath);
						Log_.out(TAG, "try to set bitmap to ImageView");
						cameraPicture.setImageBitmap(bit);
					} else {
						Log_.out(TAG, "filePath for photo is null");
					}
				}
    	         
    	    } else if (resultCode == RESULT_CANCELED) {
    	    	Log_.out(TAG, "Picture was not taken 1");
    	        //Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
    	    } else {
    	    	Log_.out(TAG, "Picture was not taken 2");
    	        //Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
    	    }
    	}
    }

}